home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2008 February / PCWFEB08.iso / Software / Freeware / Miro 1.0 / Miro_Installer.exe / Miro_Downloader.exe / xml / sax / saxutils.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2007-11-12  |  11.9 KB  |  338 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. '''A library of useful helper classes to the SAX classes, for the
  5. convenience of application and driver writers.
  6. '''
  7. import os
  8. import urlparse
  9. import urllib
  10. import types
  11. import handler
  12. import xmlreader
  13.  
  14. try:
  15.     _StringTypes = [
  16.         types.StringType,
  17.         types.UnicodeType]
  18. except AttributeError:
  19.     _StringTypes = [
  20.         types.StringType]
  21.  
  22.  
  23. try:
  24.     from codecs import xmlcharrefreplace_errors
  25.     _error_handling = 'xmlcharrefreplace'
  26.     del xmlcharrefreplace_errors
  27. except ImportError:
  28.     _error_handling = 'strict'
  29.  
  30.  
  31. def __dict_replace(s, d):
  32.     '''Replace substrings of a string using a dictionary.'''
  33.     for key, value in d.items():
  34.         s = s.replace(key, value)
  35.     
  36.     return s
  37.  
  38.  
  39. def escape(data, entities = { }):
  40.     '''Escape &, <, and > in a string of data.
  41.  
  42.     You can escape other strings of data by passing a dictionary as
  43.     the optional entities parameter.  The keys and values must all be
  44.     strings; each key will be replaced with its corresponding value.
  45.     '''
  46.     data = data.replace('&', '&')
  47.     data = data.replace('>', '>')
  48.     data = data.replace('<', '<')
  49.     if entities:
  50.         data = __dict_replace(data, entities)
  51.     
  52.     return data
  53.  
  54.  
  55. def unescape(data, entities = { }):
  56.     '''Unescape &, <, and > in a string of data.
  57.  
  58.     You can unescape other strings of data by passing a dictionary as
  59.     the optional entities parameter.  The keys and values must all be
  60.     strings; each key will be replaced with its corresponding value.
  61.     '''
  62.     data = data.replace('<', '<')
  63.     data = data.replace('>', '>')
  64.     if entities:
  65.         data = __dict_replace(data, entities)
  66.     
  67.     return data.replace('&', '&')
  68.  
  69.  
  70. def quoteattr(data, entities = { }):
  71.     '''Escape and quote an attribute value.
  72.  
  73.     Escape &, <, and > in a string of data, then quote it for use as
  74.     an attribute value.  The " character will be escaped as well, if
  75.     necessary.
  76.  
  77.     You can escape other strings of data by passing a dictionary as
  78.     the optional entities parameter.  The keys and values must all be
  79.     strings; each key will be replaced with its corresponding value.
  80.     '''
  81.     entities = entities.copy()
  82.     entities.update({
  83.         '\n': ' ',
  84.         '\r': ' ',
  85.         '\t': ' ' })
  86.     data = escape(data, entities)
  87.     if '"' in data:
  88.         if "'" in data:
  89.             data = '"%s"' % data.replace('"', '"')
  90.         else:
  91.             data = "'%s'" % data
  92.     else:
  93.         data = '"%s"' % data
  94.     return data
  95.  
  96.  
  97. class XMLGenerator(handler.ContentHandler):
  98.     
  99.     def __init__(self, out = None, encoding = 'iso-8859-1'):
  100.         if out is None:
  101.             import sys
  102.             out = sys.stdout
  103.         
  104.         handler.ContentHandler.__init__(self)
  105.         self._out = out
  106.         self._ns_contexts = [
  107.             { }]
  108.         self._current_context = self._ns_contexts[-1]
  109.         self._undeclared_ns_maps = []
  110.         self._encoding = encoding
  111.  
  112.     
  113.     def _write(self, text):
  114.         if isinstance(text, str):
  115.             self._out.write(text)
  116.         else:
  117.             self._out.write(text.encode(self._encoding, _error_handling))
  118.  
  119.     
  120.     def startDocument(self):
  121.         self._write('<?xml version="1.0" encoding="%s"?>\n' % self._encoding)
  122.  
  123.     
  124.     def startPrefixMapping(self, prefix, uri):
  125.         self._ns_contexts.append(self._current_context.copy())
  126.         self._current_context[uri] = prefix
  127.         self._undeclared_ns_maps.append((prefix, uri))
  128.  
  129.     
  130.     def endPrefixMapping(self, prefix):
  131.         self._current_context = self._ns_contexts[-1]
  132.         del self._ns_contexts[-1]
  133.  
  134.     
  135.     def startElement(self, name, attrs):
  136.         self._write('<' + name)
  137.         for name, value in attrs.items():
  138.             self._write(' %s=%s' % (name, quoteattr(value)))
  139.         
  140.         self._write('>')
  141.  
  142.     
  143.     def endElement(self, name):
  144.         self._write('</%s>' % name)
  145.  
  146.     
  147.     def startElementNS(self, name, qname, attrs):
  148.         if name[0] is None:
  149.             name = name[1]
  150.         else:
  151.             name = self._current_context[name[0]] + ':' + name[1]
  152.         self._write('<' + name)
  153.         for pair in self._undeclared_ns_maps:
  154.             self._write(' xmlns:%s="%s"' % pair)
  155.         
  156.         self._undeclared_ns_maps = []
  157.         for name, value in attrs.items():
  158.             name = self._current_context[name[0]] + ':' + name[1]
  159.             self._write(' %s=%s' % (name, quoteattr(value)))
  160.         
  161.         self._write('>')
  162.  
  163.     
  164.     def endElementNS(self, name, qname):
  165.         if name[0] is None:
  166.             name = name[1]
  167.         else:
  168.             name = self._current_context[name[0]] + ':' + name[1]
  169.         self._write('</%s>' % name)
  170.  
  171.     
  172.     def characters(self, content):
  173.         self._write(escape(content))
  174.  
  175.     
  176.     def ignorableWhitespace(self, content):
  177.         self._write(content)
  178.  
  179.     
  180.     def processingInstruction(self, target, data):
  181.         self._write('<?%s %s?>' % (target, data))
  182.  
  183.  
  184.  
  185. class XMLFilterBase(xmlreader.XMLReader):
  186.     """This class is designed to sit between an XMLReader and the
  187.     client application's event handlers.  By default, it does nothing
  188.     but pass requests up to the reader and events on to the handlers
  189.     unmodified, but subclasses can override specific methods to modify
  190.     the event stream or the configuration requests as they pass
  191.     through."""
  192.     
  193.     def __init__(self, parent = None):
  194.         xmlreader.XMLReader.__init__(self)
  195.         self._parent = parent
  196.  
  197.     
  198.     def error(self, exception):
  199.         self._err_handler.error(exception)
  200.  
  201.     
  202.     def fatalError(self, exception):
  203.         self._err_handler.fatalError(exception)
  204.  
  205.     
  206.     def warning(self, exception):
  207.         self._err_handler.warning(exception)
  208.  
  209.     
  210.     def setDocumentLocator(self, locator):
  211.         self._cont_handler.setDocumentLocator(locator)
  212.  
  213.     
  214.     def startDocument(self):
  215.         self._cont_handler.startDocument()
  216.  
  217.     
  218.     def endDocument(self):
  219.         self._cont_handler.endDocument()
  220.  
  221.     
  222.     def startPrefixMapping(self, prefix, uri):
  223.         self._cont_handler.startPrefixMapping(prefix, uri)
  224.  
  225.     
  226.     def endPrefixMapping(self, prefix):
  227.         self._cont_handler.endPrefixMapping(prefix)
  228.  
  229.     
  230.     def startElement(self, name, attrs):
  231.         self._cont_handler.startElement(name, attrs)
  232.  
  233.     
  234.     def endElement(self, name):
  235.         self._cont_handler.endElement(name)
  236.  
  237.     
  238.     def startElementNS(self, name, qname, attrs):
  239.         self._cont_handler.startElementNS(name, qname, attrs)
  240.  
  241.     
  242.     def endElementNS(self, name, qname):
  243.         self._cont_handler.endElementNS(name, qname)
  244.  
  245.     
  246.     def characters(self, content):
  247.         self._cont_handler.characters(content)
  248.  
  249.     
  250.     def ignorableWhitespace(self, chars):
  251.         self._cont_handler.ignorableWhitespace(chars)
  252.  
  253.     
  254.     def processingInstruction(self, target, data):
  255.         self._cont_handler.processingInstruction(target, data)
  256.  
  257.     
  258.     def skippedEntity(self, name):
  259.         self._cont_handler.skippedEntity(name)
  260.  
  261.     
  262.     def notationDecl(self, name, publicId, systemId):
  263.         self._dtd_handler.notationDecl(name, publicId, systemId)
  264.  
  265.     
  266.     def unparsedEntityDecl(self, name, publicId, systemId, ndata):
  267.         self._dtd_handler.unparsedEntityDecl(name, publicId, systemId, ndata)
  268.  
  269.     
  270.     def resolveEntity(self, publicId, systemId):
  271.         return self._ent_handler.resolveEntity(publicId, systemId)
  272.  
  273.     
  274.     def parse(self, source):
  275.         self._parent.setContentHandler(self)
  276.         self._parent.setErrorHandler(self)
  277.         self._parent.setEntityResolver(self)
  278.         self._parent.setDTDHandler(self)
  279.         self._parent.parse(source)
  280.  
  281.     
  282.     def setLocale(self, locale):
  283.         self._parent.setLocale(locale)
  284.  
  285.     
  286.     def getFeature(self, name):
  287.         return self._parent.getFeature(name)
  288.  
  289.     
  290.     def setFeature(self, name, state):
  291.         self._parent.setFeature(name, state)
  292.  
  293.     
  294.     def getProperty(self, name):
  295.         return self._parent.getProperty(name)
  296.  
  297.     
  298.     def setProperty(self, name, value):
  299.         self._parent.setProperty(name, value)
  300.  
  301.     
  302.     def getParent(self):
  303.         return self._parent
  304.  
  305.     
  306.     def setParent(self, parent):
  307.         self._parent = parent
  308.  
  309.  
  310.  
  311. def prepare_input_source(source, base = ''):
  312.     '''This function takes an InputSource and an optional base URL and
  313.     returns a fully resolved InputSource object ready for reading.'''
  314.     if type(source) in _StringTypes:
  315.         source = xmlreader.InputSource(source)
  316.     elif hasattr(source, 'read'):
  317.         f = source
  318.         source = xmlreader.InputSource()
  319.         source.setByteStream(f)
  320.         if hasattr(f, 'name'):
  321.             source.setSystemId(f.name)
  322.         
  323.     
  324.     if source.getByteStream() is None:
  325.         sysid = source.getSystemId()
  326.         basehead = os.path.dirname(os.path.normpath(base))
  327.         sysidfilename = os.path.join(basehead, sysid)
  328.         if os.path.isfile(sysidfilename):
  329.             source.setSystemId(sysidfilename)
  330.             f = open(sysidfilename, 'rb')
  331.         else:
  332.             source.setSystemId(urlparse.urljoin(base, sysid))
  333.             f = urllib.urlopen(source.getSystemId())
  334.         source.setByteStream(f)
  335.     
  336.     return source
  337.  
  338.